<?php
class FunctionAction extends CommonAction {
    // 框架首页

    /*+---------------------
      |    添加功能         
      +---------------------
     */
    public function addFunction(){
        $t_function = D("function");
        if($_POST['confirm']){
            $this->checkFunctionInfo($_POST);  //检查功能信息是否有重复
            $data = $_POST;
            $data['create_user'] = $_SESSION['authId'];
            $data['create_time'] = toDate(time());
            $result = $t_function ->add($data);
            if($result){
                if($data['pid'] == "0"){
                    $path['path'] = $data['pid'].",".$result;
                }else{
                    $path = $t_function ->field("path")->where("id={$data['pid']}")->find();
                    $path['path'] = $path['path'].",".$result;
                }
                $path['id']   = $result;
                $re   = $t_function ->save($path);
				$this->updateWebsiteDatabase();    //更新站点数据库功能表
                if($re){
                    $this->success("新增功能成功!");
                }else{
                    $this->error("修改PATH失败!");
                }

            }else{
                $this->error("新增功能失败!");
            }
        }
        $this->assign("functionNames",$this->getFunctionTree());
        $this->display();
        
    }

    /*+--------------------------------------
      |      检查功能信息，防止功能信息重复
      +--------------------------------------
     */
    public function checkFunctionInfo($info){
           $t_function = D("function");
           if($info['function_title'] == ""){
                 $this->error("显示名不能为空~~~");
           }else{
                if($info['id']){
                      $where = "function_title = '{$info['function_title']}' and id != {$info['id']}";
                }else{
                      $where = "function_title = '{$info['function_title']}'";
                }

                $check_title = $t_function ->where($where)->find();
                if($check_title){
                        $this->error("功能名称已经存在，不允许重复添加！");
                }
           }
           if($info['function_act'] != "" && $info['function_app'] != "" ){
                if($info['id']){
                      $where = "function_act = '{$info['function_act']}' and function_app = '{$info['function_app']}' and id != {$info['id']}";
                }else{
                      $where = "function_act = '{$info['function_act']}' and function_app = '{$info['function_app']}'";
                }
                 $require = $t_function ->where($where)->find();
                 if($require){
                        $this->error("此功能配置已经存在，不允许重复添加！");
                 }
            }
    }

    /*+--------------------------------------
      |      显示功能
      +--------------------------------------
      |      显示所有的功能
      +--------------------------------------
     */
    public function selectFunction(){
        $url             = U("Function/showFunction");
        $param['after']  = '&nbsp;<input type="checkbox" name="id[]" value="PK"/>&nbsp;&nbsp;<a href="'.$url.'/Fid/PK">查看</a>';
        $param['link']   = "0";
        $allFunction = $this->get_menu(0,$param);    
        $this->assign("allFunction",$allFunction);
        $this->display();
    }

    /*+---------------------------------------
      |     显示功能的详细信息
      +---------------------------------------
      |     显示所有功能
      +---------------------------------------
      * */
    public function showFunction(){
        if($_GET['Fid']){
               $where = "id = {$_GET['Fid']}";
        }
        if($_POST['id']){
               foreach($_POST['id'] as $key => $val){
                      $in .= $val.",";
               }
               $in    = rtrim($in,",");
               $where = "id in ({$in})";
        }
        $show         = D("function");
        $showFunction = $show->where($where)->select();
        foreach($showFunction as $key => $val){
                foreach($val as $k => $v){
                    if($k == "pid"){
                       if($v == "0"){
                              $showFunction[$key][$k] = "导航栏功能";
                       }else{
                              $name = $show ->field("function_title")->find($v);
                              $showFunction[$key][$k]= $name['function_title'];
                       }
                    }
                }
        }
        
        $this->assign("showFunction",$showFunction);
        $this->display();
    }

    /*+------------------------------------------------------
      |   编辑功能
      +------------------------------------------------------
      |   支持多项选择
      +------------------------------------------------------
      |   如果想插入主键ID，只需将在出入的位置使用PK代替
      +------------------------------------------------------
     */
    public function editFunction(){
        $url             = U("Function/changeFunction");
        $param['after']  = '&nbsp;<input type="checkbox" name="id[]" value="PK"/>&nbsp;&nbsp;<a href="'.$url.'/Fid/PK">编辑</a>';
        $param['link']   = "0";
        $editFunctions   = $this->get_menu(0,$param);
        $this->assign("editFunctions",$editFunctions);
        $this->display();
    }

    /*+---------------------------------------
      |    编辑页面
      +---------------------------------------
      |    支持多项同时编辑
      +---------------------------------------
     */
     public function changeFunction(){
            if($_GET['Fid']){
                $where = "id = ".$_GET['Fid'];
            }
            if($_POST['edit']){
                foreach($_POST['id'] as $key => $val){
                     $in .= $val.",";
                }
                $in    = rtrim($in,",");
                $where = "id in ({$in})"; 
            }
            $edit     = D("function");    
            $editList = $edit->where($where)->select();
            foreach($editList as $key => $val){
                foreach($val as $k => $v){
                    if($k == "pid"){
                          $editList[$key]['tree'] = $this->getFunctionTree($v);
                    }
                }
            }
            //echo "<pre>";
            //print_r($editList);
            //exit;
            //echo "<pre>";
            //print_r($editList);
            $this->assign("editList",$editList);
            

            $this->display();
     }
    
    /*+----------------------------------------
      |     执行编辑
      +----------------------------------------
    */
    public function executeEdit(){
        if($_POST['edit']){
                  $edit         = D("function");
                  foreach($_POST as $key => $val){
                      if($key != "edit" && $key != "__hash__"){
                            foreach($val as $k => $v){
                                 $data[$k][$key]=$v;
                            }
                      }
                  }
                  foreach($data as $key => $val){
                        $this ->checkFunctionInfo($val);   //在修改之前，先检查是否有不允许的重复
                        //查找父类别的Path
                        $path         = $edit->field("path")->where("id = {$val['pid']}")->find();
                        $val['path']  = $path['path'].",".$val['id']; 
						
                        //echo "<pre>";print_r($val);exit;
                        $updateResult+= $edit -> save($val);
						$this->updateWebsiteDatabase();
                  }
                  if($updateResult){
                          $this->assign("jumpUrl","editFunction");
                          $this->success("成功修改：{$updateResult} 条!");
                  }else{
                          $this->error("修改失败！");
                  }
           }
    }

    /*+------------------------------------------
      |    显示删除功能
      +------------------------------------------
      * */
    public function delFunction(){
        $url             = U("Function/executeDel");
        $param['after']  = '&nbsp;<input type="checkbox" name="id[]" value="PK"/>&nbsp;&nbsp;<a href="'.$url.'/Fid/PK" onclick="return confirm(\'警告：\n\t您确定要删除此项功能么？\')">删除</a>';
        $param['link']   = "0";
        $delFunctions   = $this->get_menu(0,$param);
        $this->assign("delFunctions",$delFunctions);
        $this->display();
    }

    public function executeDel(){
        $del       = D("function");        
        if($_GET['Fid']){
              $where     = "id = {$_GET['Fid']}";
        }

        if($_POST['del']){
            foreach($_POST['id'] as $key => $val){
                $pids  .= $val.",";
                if($this->checkChildFunc($val)){
                        $pids  .= $this->checkChildFunc($val).",";
                }
            }
            $pids  = rtrim($pids,",");
            //$num =count(explode(",",$pids));
            //echo $num; 
            $where = "id in ({$pids})";
            
        }

        $delResult = $del ->where($where)->delete();
		$this->updateWebsiteDatabase();    //更新站点数据库功能表
        if($delResult){
                $this->assign("jumpUrl","delFunction");
                $this->success("成功的删除了：{$delResult} 个功能！");
        }else{
                $this->error("删除失败！");
        }
    }

    public function checkChildFunc($pid){
	    $func     = D("function");
        $pid_list = $func->field("id")->where("pid={$pid}")->select();
        if($pid_list){
            $pid_str  = $this->diguiCheck($pid_list);   //无限分类，递归调用
            $pid_str  = rtrim($pid_str,",");
        }
        return $pid_str;
	}

	public function diguiCheck($list){
        $func = D("function");
        if($list){
		foreach($list as $key=>$val){
			
			$pid_str .= $val["id"].",";
			$pid_list = $func ->field("id")->where("pid=".$val['id'])->select();
			if(count($pid_list)>0){
			       $pid_str .= $this->diguiCheck($pid_list);
            }
			
        }
        }
		return $pid_str;
	}
	
	/*+-------------------------------------+
	  |     更新站点数据库功能表               |
	  +-------------------------------------+*/
	public function updateWebsiteDatabase(){
	       //如果修改站点的功能时，同步修改所有站点数据库的功能表中的功能信息
		   //1.获取所有的站点数据库名称
		   $webDB     = D("website");
		   $websiteDB = $webDB -> field("database")->select();
		   $insert    = $this->getFunctionInsertSQL();
		   $database  = new Model();
		   foreach($websiteDB as $key => $val){
				   //2.切换每个站点数据库，执行功能信息全部更新
				   $database ->query("use {$val['database']}");
				   $database ->query("delete from douhao_function");
				   $database ->query($insert);
				   
		   }
		   //3.切回主数据库
		   $database ->query("use dhjdsj_douhaosystem");
		   //echo $insert;

	}
	
	

}
?>

